package com.sqbang.dbcompare.pojo.model;


import org.springframework.http.HttpStatus;

import java.io.Serializable;
import java.util.HashMap;

/**
 * 响应数据对象
 * @author suqiongbang
 * @date 2020/12/28 20:38
 */
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private int code;

    private String msg;

    private T result;

    public static R ok() {
        return ok(HttpStatus.OK.value(), HttpStatus.OK.getReasonPhrase());
    }

    public static <K> R<K> ok(K data) {
        R<K> resp = ok();
        resp.setResult(data);
        return resp;
    }

    @Deprecated
    public static <K> R<K> ok(int code, String msg, K data) {
        R<K> resp = new R<>();
        resp.setCode(code);
        resp.setMsg(msg);
        resp.setResult(data);
        return resp;
    }

    public static R<String> ok(int code, String msg) {
        R<String> resp = new R<>();
        resp.setCode(code);
        resp.setMsg(msg);
        return resp;
    }

    public static <K> R<K> ok(String msg, K data) {
        R resp = ok(msg);
        resp.setResult(data);
        return resp;

    }


    public static R error(int errorCode, String msg) {
        R resp = new R();
        resp.setCode(errorCode);
        resp.setMsg(msg);
        return resp;
    }

    public static R error(String msg) {
        return error(HttpStatus.INTERNAL_SERVER_ERROR.value(), msg);
    }


    @Deprecated
    public static R error() {
        return error(HttpStatus.INTERNAL_SERVER_ERROR.value(), HttpStatus.INTERNAL_SERVER_ERROR.getReasonPhrase());
    }

    @Deprecated
    public static <K> R<K> error(K data) {
        R<K> resp = error();
        resp.setResult(data);
        return resp;
    }

    public static R error(HttpStatus status) {
        R resp = new R();
        resp.setCode(status.value());
        resp.setMsg(status.getReasonPhrase());
        return resp;
    }

    public int getCode() {
        return code;
    }

    public String getMsg() {
        return msg;
    }

    public T getResult() {
        return result;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    private void setResult(T result) {
        this.result = result;
    }

    public boolean success() {
        return this.code == HttpStatus.OK.value();
    }
}
